package wine.web;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.lang.reflect.ParameterizedType;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.SessionAware;

import wine.ejb.utilities.Constants;
import wine.ejb.utilities.Log;
import wine.ejb.utilities.PageInfo;
import wine.ejb.utilities.PagedResults;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class Struts2Support<T> extends EjbSupport implements SessionAware,
		ServletRequestAware, ActionIFace {

	private static final long serialVersionUID = 1L;

	protected Class<T> entityClass;

	protected HttpServletRequest request;

	protected Map<String, Object> sessionMap;

	protected Map<String, Object> jsonMap = new HashMap<String, Object>();
	// protected int firstResult;

	// protected Integer pageIndex = 1;
	//
	// protected Integer pageSize = 15;
	//
	// protected Integer pageTotal;
	//
	// protected Integer recordCount;

	protected List<T> lst;
	protected T obj;
	protected String message = "";

	protected PagedResults<T> pagedResults;

	protected PageInfo pageInfo = new PageInfo();

	protected Integer curr_org_id = null;
	protected Long distId = null;

	protected String fileName = null;
	protected String filePath = null;
	@Override
	public void validate() {
		// TODO Auto-generated method stub
		this.readSessionValues();
		super.validate();
	}

	@Override
	public String execute() throws Exception {
		return super.execute();
	}

	@Override
	public void setSession(Map<String, Object> sessionMap) {
		this.sessionMap = sessionMap;
	}

	public void addToSession(String objName, Object obj) {
		request.getSession().setAttribute(objName, obj);
	}

	public void removeAllSession() {
		try {
			Enumeration<?> e = this.request.getSession().getAttributeNames();
			while (e.hasMoreElements()) {
				String sessionName = (String) e.nextElement();
				this.request.getSession().removeAttribute(sessionName);
			}
		} catch (Exception ex) {
			LOG.debug("session已被清空");
		}
	}

	public Object readSession(String objName) {
		return request.getSession().getAttribute(objName);
	}

	@Override
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}

	/*protected Object lookupDao(Class implClass) {
		try {
			Context ctx = new InitialContext();
			Log.debug(implClass.getSimpleName());
			return ctx.lookup(implClass.getSimpleName() + "/remote");
		} catch (Exception e) {
			// TODO: handle exception
			Log.error(e.getMessage());
			return null;
		}
	}
	protected Object lookupLocalDao(Class implClass) {
		try {
			Context ctx = new InitialContext();
			Log.debug(implClass.getSimpleName());
			return ctx.lookup(implClass.getSimpleName() + "/local");
		} catch (Exception e) {
			// TODO: handle exception
			Log.error(e.getMessage());
			return null;
		}
	}*/

	public List<T> getLst() {
		return this.lst;
	}

	public void setLst(List<T> lst) {
		this.lst = lst;
	}

	public T getObj() {
		return this.obj;
	}

	public void setObj(T obj) {
		this.obj = obj;
	}

	public Long getDistId() {
		return distId;
	}

	public void setDistId(Long distId) {
		this.distId = distId;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public Map<String, Object> getJsonMap() {
		return jsonMap;
	}

	@Override
	public String add() {
		// TODO Auto-generated method stub
		try {
			Log.debug("creating Object.");
			this.obj = this.entityClass.newInstance();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return SUCCESS;
	}

	@Override
	public String findById() {
		// TODO Auto-generated method stub
		return SUCCESS;
	}

	@Override
	public String findList() {
		// TODO Auto-generated method stub

		// 分页设置。。。

		// if ((pagedResults != null) && (pagedResults.getRecordCount() !=
		// null)) {
		// recordCount = pagedResults.getRecordCount();
		// }
		//
		// pageTotal = recordCount % pageSize > 0 ? recordCount / pageSize + 1
		// : recordCount / pageSize;
		// pageIndex = pageIndex > pageTotal ? pageTotal : pageIndex;

		if (this.pagedResults != null) {
			this.pageInfo = this.pagedResults.getPageInfo();
			this.lst = this.pagedResults.getResultList();
		}
		return SUCCESS;
	}

	@Override
	public String remove() {
		// TODO Auto-generated method stub
		return SUCCESS;
	}

	@Override
	public String save() {
		// TODO Auto-generated method stub
		return SUCCESS;
	}

	public PagedResults<T> getPagedResults() {
		return this.pagedResults;
	}

	public void setPagedResults(PagedResults<T> pagedResults) {
		this.pagedResults = pagedResults;
	}

	@SuppressWarnings("unchecked")
	public Struts2Support() {
		super();
		if (!pageInfo.isSwitchingPage()) {
			this.pageInfo = new PageInfo();
		}
		// TODO Auto-generated constructor stub
		this.entityClass = (Class<T>) ((ParameterizedType) this.getClass()
				.getGenericSuperclass()).getActualTypeArguments()[0];
		Log.debug(this.entityClass.getSimpleName());
		try {
			this.obj = this.entityClass.newInstance();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public PageInfo getPageInfo() {
		return this.pageInfo;
	}

	public void setPageInfo(PageInfo pageInfo) {
		this.pageInfo = pageInfo;
	}

	private void readSessionValues() {
		if (this.request.getSession() != null) {
			Object _tmp = this.request.getSession().getAttribute(
					Constants.LOGIN_USER_INFO);
			if (_tmp != null) {
				//this.loginUser = (SysUsrInf) _tmp;
			}
		}
	}

	/*public void printReport(String jasperFile, Map params) {
		HttpServletResponse response = ServletActionContext.getResponse();
		ServletOutputStream servletOutputStream = null;
		try {
			servletOutputStream = response.getOutputStream();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		InputStream reportStream = ServletActionContext.getServletContext()
				.getResourceAsStream(jasperFile);

		Context ctx = null;
		Connection conn = null;
		try {
			ctx = new InitialContext();
			DataSource dts = (DataSource) ctx.lookup("java:xinstru-JXC");
			conn = dts.getConnection();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		try {
			JasperRunManager.runReportToPdfStream(reportStream,
					servletOutputStream, params, conn);
			conn.close();
		} catch (JRException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e1) {
					e1.printStackTrace();
				}
			}
			e.printStackTrace();
		}
		response.setContentType("text/html");
		try {

			servletOutputStream.flush();
			servletOutputStream.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	*/
	public void createFile(Map dataMap, String ftlName,String outName)  {
		Configuration configuration = null;
		configuration = new Configuration();
		configuration.setDefaultEncoding("utf-8");
		try {
			configuration.setDirectoryForTemplateLoading(new File(
					ServletActionContext.getServletContext().getRealPath("/WEB-INF")));
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		Template t = null;
		try {
			t = configuration.getTemplate(ftlName);
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 输出文档路径及名称
		String pathStr = ServletActionContext.getServletContext().getRealPath("/");
		File f = new File(pathStr+"/files/");
		if(!f.exists()){
			f.mkdirs();
		}
		File outFile = new File(pathStr+"/files/"+outName);
		Writer out = null;		
		try {
			  out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"utf-8")); 
			  t.process(dataMap, out);
		} catch (TemplateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			this.filePath="{'filePath':'files/"+outName+"'}";
		}
	}

	public String getFilePath() {
		return filePath;
	}

	public void setFilePath(String filePath) {
		this.filePath = filePath;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}
}
